package reponse

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"shopstar/core/validate"
	"strings"
)

func HandleValidateError(ctx *gin.Context, err error) {
	errs, ok := err.(validator.ValidationErrors) // 获取验证器返回的错误信息
	if !ok {
		//ctx.JSON(http.StatusOK, gin.H{
		//	"msg": err.Error(),
		//})
		FailWithDatailed(errs, "验证错误", ctx)
		return
	}

	FailWithDatailed(removeTopStruct(errs.Translate(validate.Trans)), "验证错误", ctx)
	//ctx.JSON(http.StatusBadRequest, gin.H{
	//	"error": removeTopStruct(errs.Translate(validate.Trans)), // 返回错误信息
	//})
}

func removeTopStruct(fileds map[string]string) map[string]string {
	rsp := map[string]string{}

	for filed, err := range fileds {
		if err == "" {
			err = validate.Err.String()
		}
		rsp[filed[strings.Index(filed, ".")+1:]] = err
	}
	return rsp
}
